#include <system.h>

#define vga_width 80
#define vga_height 25

unsigned short* vgatext = 0xB8000 + Higher_Half_Address;
unsigned char vgacolor = 0x0F;
int vgacx = 0, vgacy = 0;


void vga_scroll()
{
 if(vgacy >= 25)
 {
  memcpy(vgatext,vgatext+vga_width,vga_width*(vga_height-1)*2);
  memsetw(vgatext+(vga_width*(vga_height-1))-1,(vgacolor<<8) | ' ',vga_width);
  vgacy = vga_height-1;
 } 
}

void vga_cls()
{
 memsetw(vgatext,(vgacolor<<8) | ' ',vga_width*vga_height);
 vgacx = 0;
 vgacy = 0;
 vga_movecursor();
}

void vga_settextcolor(unsigned char forecolor, unsigned char backcolor)
{
 vgacolor = (backcolor << 4) | (forecolor & 0xF);
}

void vga_init()
{
 vga_cls();
}

// Not mine
void vga_movecursor()
{
 unsigned temp;

 temp = vgacy * 80 + vgacx;

 /* This sends a command to indicies 14 and 15 in the
  *  CRT Control Register of the VGA controller. These
  *  are the high and low bytes of the index that show
  *  where the hardware cursor is to be 'blinking'. To
  *  learn more, you should look up some VGA specific
  *  programming documents. A great start to graphics:
  *  http://www.brackeen.com/home/vga
  */
 outportb(0x3D4, 14);
 outportb(0x3D5, temp >> 8);
 outportb(0x3D4, 15);
 outportb(0x3D5, temp);
}

void vga_setcursor(unsigned char x, unsigned char y)
{
 vgacx = x;
 vgacy = y;

 vga_movecursor();
}

void vga_printchar(unsigned char c)
{
 if(c == '\b')
  vgacx = vgacx ? vgacx-- : 0,
  vgatext[(vgacy*vga_width)+vgacx] = (vgacolor << 8) | ' ';
 else if(c == '\t')
  vgacx = (vgacx+8) & 0xF8;
 else if(c == '\r')
  vgacx = 0;
 else if(c == '\n')
  vgacx = 0,
  vgacy++;
 else
  vgatext[(vgacy*vga_width)+vgacx] = (vgacolor << 8) | c,
  vgacx++;

 vga_scroll();
 vga_movecursor();
}

void vga_printstr(unsigned char* str)
{
 int i, l = strlen(str);
 for(i = 0; i < l; i++)
  vga_printchar(str[i]);
}

void vga_setsquare(unsigned char c, unsigned char x, unsigned char y)
{
 vgatext[(y*vga_width)+x] = (vgacolor << 8) | c;
}